import { Message, Modal } from '@arco-design/web-vue';
import { defineStore } from 'pinia';
import { computed, reactive, toRefs } from 'vue';
import { delData, savetData } from './api';
export const useAdminStore = defineStore('admin', () => {
  const model = () => ({
    username: ``,
    password: ``,
    role: ``,
    avatar: ``,
    state: 1,
  });
  const state = reactive({
    status: false,
    formRef: null,
    rules: {
      username: [{ required: true, message: '请输入手机号' }],
      password: computed(() =>
        !state.form?.id ? [{ required: true, message: '请输入密码' }] : []
      ),
      nickname: [{ required: true, message: '请输入昵称' }],
      avatar: [{ required: true, message: '请上传照片' }],
      role: [{ required: true, message: '请选择角色' }],
      state: [{ required: true, message: '状态' }],
    },
    options: {
      roles: [],
    },
    rowSelection: {
      showCheckedAll: true,
      type: 'checkbox',
    },
    selectedKeys: [],
    form: model(),
    fetchData: null,
    async handleBeforeOk(done) {
      const vaild = !!(await state.formRef.validate());
      if (vaild) {
        done(false);
        console.error(state.form);
        return;
      }
      console.log('success');
      await savetData(state.form);
      Message.success(state.form?.id ? '编辑成功' : '新建成功');
      state.status = false;
      state.fetchData();
    },
    open(focusRef, formRef) {
      focusRef.focus();
      state.formRef = formRef;
    },
    async add() {
      console.log(state);
      state.status = true;
      state.form = model();
    },
    async dels(fetchData) {
      const ids = state.selectedKeys.join(',');
      console.log(ids);
      if (!ids) {
        Message.warning('请选择要删除的菜单');
        return;
      }
      Modal.error({
        title: '操作提示',
        content: '是否确认删除所选菜单?',
        async onOk() {
          await state.del(ids, fetchData);
        },
      });
    },
    async del(id, fetchData) {
      await delData(id);
      Message.success('删除成功');
      state.fetchData();
    },
    edit(record) {
      Object.assign(state.form, {
        ...record,
      });
      state.status = true;
    },
  });
  return {
    ...toRefs(state),
  };
});

export default useAdminStore;
